const express = require('express');
const { query } = require('../config/database');
const { authenticateToken } = require('../middleware/auth');
const axios = require('axios');

const router = express.Router();

// 职业匹配算法 - 多维度评分系统
class CareerMatcher {
  constructor() {
    this.weights = {
      skills: 0.35,        // 技能匹配权重
      education: 0.20,      // 学历匹配权重
      experience: 0.15,     // 经验匹配权重
      interests: 0.15,      // 兴趣匹配权重
      fileContent: 0.10,    // 文件内容匹配权重
      category: 0.05        // 职业分类匹配权重
    };
  }

  // 计算技能匹配分数
  calculateSkillsScore(userSkills, careerSkills) {
    if (!userSkills || !careerSkills || careerSkills.length === 0) return 0;
    
    const userSkillSet = new Set(userSkills.map(skill => skill.toLowerCase()));
    const careerSkillSet = new Set(careerSkills.map(skill => skill.toLowerCase()));
    
    const intersection = [...userSkillSet].filter(skill => careerSkillSet.has(skill));
    const union = [...new Set([...userSkillSet, ...careerSkillSet])];
    
    return union.length > 0 ? (intersection.length / union.length) * 100 : 0;
  }

  // 计算学历匹配分数
  calculateEducationScore(userGrade, careerEducation) {
    if (!userGrade || !careerEducation) return 50; // 默认中等分数
    
    const educationLevels = {
      '高中': 1, '专科': 2, '本科': 3, '硕士': 4, '博士': 5
    };
    
    const userLevel = educationLevels[userGrade] || 2;
    const careerLevel = educationLevels[careerEducation] || 3;
    
    if (userLevel >= careerLevel) return 100;
    if (userLevel >= careerLevel - 1) return 80;
    if (userLevel >= careerLevel - 2) return 60;
    return 30;
  }

  // 计算经验匹配分数
  calculateExperienceScore(userGrade, careerExperience) {
    if (!userGrade || !careerExperience) return 50;
    
    // 根据年级估算经验
    const gradeToExperience = {
      '大一': 0, '大二': 0.5, '大三': 1, '大四': 1.5,
      '研一': 2, '研二': 2.5, '研三': 3,
      '博一': 3, '博二': 3.5, '博三': 4, '博四': 4.5
    };
    
    const userExp = gradeToExperience[userGrade] || 1;
    
    // 解析职业经验要求
    const expMatch = careerExperience.match(/(\d+)-?(\d+)?/);
    if (!expMatch) return 50;
    
    const minExp = parseInt(expMatch[1]);
    const maxExp = expMatch[2] ? parseInt(expMatch[2]) : minExp + 2;
    
    if (userExp >= minExp && userExp <= maxExp) return 100;
    if (userExp >= minExp - 1) return 80;
    if (userExp >= minExp - 2) return 60;
    return 30;
  }

  // 计算兴趣匹配分数
  calculateInterestsScore(userInterests, careerDescription) {
    if (!userInterests || !careerDescription) return 50;
    
    const interestKeywords = userInterests.map(interest => interest.toLowerCase());
    const careerText = careerDescription.toLowerCase();
    
    let matchCount = 0;
    interestKeywords.forEach(interest => {
      if (careerText.includes(interest)) matchCount++;
    });
    
    return interestKeywords.length > 0 ? (matchCount / interestKeywords.length) * 100 : 50;
  }

  // 使用AI分析文件内容
  async analyzeFileContent(userId) {
    try {
      // 获取用户文件列表
      const files = await query(
        'SELECT file_name, file_type, mime_type FROM cloud_files WHERE user_id = ? AND file_type = "file"',
        [userId]
      );
      
      if (files.length === 0) return null;
      
      // 构建文件内容摘要
      const fileSummary = files.map(file => ({
        name: file.file_name,
        type: file.file_type,
        mime: file.mime_type
      }));
      
      // 调用AI分析文件内容
      const prompt = `请分析以下用户文件，提取与职业发展相关的技能、兴趣和专业领域信息：
      
文件列表：
${fileSummary.map(f => `- ${f.name} (${f.type})`).join('\n')}

请返回JSON格式的分析结果：
{
  "skills": ["技能1", "技能2"],
  "interests": ["兴趣1", "兴趣2"],
  "domains": ["领域1", "领域2"],
  "summary": "整体分析摘要"
}`;

      const response = await axios.post('https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation', {
        model: process.env.ALIYUN_MODEL || 'qwen-flash',
        input: {
          messages: [
            {
              role: 'system',
              content: '你是一个专业的职业规划顾问，擅长分析用户文件内容来识别技能和兴趣。'
            },
            {
              role: 'user',
              content: prompt
            }
          ]
        },
        parameters: {
          max_tokens: 500,
          temperature: 0.3
        }
      }, {
        headers: {
          'Authorization': `Bearer ${process.env.ALIYUN_API_KEY}`,
          'Content-Type': 'application/json'
        },
        timeout: 10000
      });

      if (response.data && response.data.output && response.data.output.text) {
        try {
          let text = response.data.output.text;
          // 处理markdown代码块
          if (text.includes('```json')) {
            text = text.replace(/```json\n?/g, '').replace(/```\n?/g, '');
          }
          return JSON.parse(text);
        } catch (parseError) {
          console.error('AI响应解析失败:', parseError);
          return null;
        }
      }
      
      return null;
    } catch (error) {
      console.error('AI分析文件内容失败:', error);
      return null;
    }
  }

  // 计算文件内容匹配分数
  calculateFileContentScore(fileAnalysis, careerDescription, careerSkills) {
    if (!fileAnalysis) return 50;
    
    let score = 0;
    let factors = 0;
    
    // 技能匹配
    if (fileAnalysis.skills && fileAnalysis.skills.length > 0) {
      const skillScore = this.calculateSkillsScore(fileAnalysis.skills, careerSkills || []);
      score += skillScore;
      factors++;
    }
    
    // 领域匹配
    if (fileAnalysis.domains && fileAnalysis.domains.length > 0) {
      const careerText = (careerDescription + ' ' + (careerSkills || []).join(' ')).toLowerCase();
      const domainMatches = fileAnalysis.domains.filter(domain => 
        careerText.includes(domain.toLowerCase())
      ).length;
      const domainScore = fileAnalysis.domains.length > 0 ? 
        (domainMatches / fileAnalysis.domains.length) * 100 : 50;
      score += domainScore;
      factors++;
    }
    
    return factors > 0 ? score / factors : 50;
  }

  // 计算职业分类匹配分数
  calculateCategoryScore(userInterests, careerCategory) {
    if (!userInterests || !careerCategory) return 50;
    
    const categoryKeywords = {
      '技术开发': ['编程', '代码', '技术', '开发', '软件', '程序'],
      '设计': ['设计', '美术', '创意', '视觉', 'UI', 'UX'],
      '营销': ['营销', '推广', '销售', '市场', '广告'],
      '管理': ['管理', '领导', '团队', '项目', '运营'],
      '教育': ['教育', '教学', '培训', '学习', '知识']
    };
    
    const keywords = categoryKeywords[careerCategory] || [];
    const userInterestText = userInterests.join(' ').toLowerCase();
    
    const matches = keywords.filter(keyword => 
      userInterestText.includes(keyword.toLowerCase())
    ).length;
    
    return keywords.length > 0 ? (matches / keywords.length) * 100 : 50;
  }

  // 主匹配算法
  async calculateMatchScore(user, career, fileAnalysis = null) {
    const scores = {};
    
    // 技能匹配
    let careerSkills = [];
    try {
      if (career.skills) {
        if (typeof career.skills === 'string') {
          careerSkills = JSON.parse(career.skills);
        } else if (Array.isArray(career.skills)) {
          careerSkills = career.skills;
        }
      }
    } catch (error) {
      console.error('解析技能数据失败:', error);
      careerSkills = [];
    }
    
    scores.skills = this.calculateSkillsScore(
      user.interests || [], 
      careerSkills
    );
    
    // 学历匹配
    scores.education = this.calculateEducationScore(
      user.grade, 
      career.education_level
    );
    
    // 经验匹配
    scores.experience = this.calculateExperienceScore(
      user.grade, 
      career.experience_years
    );
    
    // 兴趣匹配
    scores.interests = this.calculateInterestsScore(
      user.interests || [], 
      career.description
    );
    
    // 文件内容匹配
    scores.fileContent = fileAnalysis ? 
      this.calculateFileContentScore(fileAnalysis, career.description, careerSkills) : 50;
    
    // 职业分类匹配
    scores.category = this.calculateCategoryScore(
      user.interests || [], 
      career.category
    );
    
    // 计算加权总分
    const totalScore = Object.keys(this.weights).reduce((sum, key) => {
      return sum + (scores[key] || 0) * this.weights[key];
    }, 0);
    
    return {
      totalScore: Math.round(totalScore),
      scores,
      weights: this.weights
    };
  }
}

// 获取职业匹配推荐
router.get('/matches', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const limit = parseInt(req.query.limit) || 20;
    
    console.log(`开始为用户 ${userId} 计算职业匹配推荐`);
    
    // 获取用户信息
    const users = await query('SELECT * FROM users WHERE id = ?', [userId]);
    if (users.length === 0) {
      return res.status(404).json({ success: false, message: '用户不存在' });
    }
    
    const user = users[0];
    
    // 使用AI分析用户文件内容
    console.log('开始分析用户文件内容...');
    const fileAnalysis = await new CareerMatcher().analyzeFileContent(userId);
    console.log('文件内容分析结果:', fileAnalysis);
    
    // 获取所有活跃的职业
    const careers = await query(
      'SELECT * FROM careers WHERE is_active = TRUE ORDER BY created_at DESC',
      []
    );
    
    console.log(`找到 ${careers.length} 个活跃职业`);
    
    if (careers.length === 0) {
      return res.json({
        success: true,
        matches: [],
        message: '暂无职业数据'
      });
    }
    
    // 使用高效算法计算匹配分数
    const matcher = new CareerMatcher();
    const matchPromises = careers.map(async (career) => {
      const matchResult = await matcher.calculateMatchScore(user, career, fileAnalysis);
      return {
        career,
        ...matchResult
      };
    });
    
    const allMatches = await Promise.all(matchPromises);
    
    // 按分数排序并取前N个
    const topMatches = allMatches
      .sort((a, b) => b.totalScore - a.totalScore)
      .slice(0, limit);
    
    // 保存匹配结果到数据库（可选）
    const savePromises = topMatches.map(async (match) => {
      try {
        await query(
          'INSERT INTO user_career_matches (user_id, career_id, match_score, match_reasons, user_skills, missing_skills) VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE match_score = VALUES(match_score), match_reasons = VALUES(match_reasons), user_skills = VALUES(user_skills), missing_skills = VALUES(missing_skills)',
          [
            userId,
            match.career.id,
            match.totalScore,
            JSON.stringify(match.scores),
            JSON.stringify(user.interests || []),
            JSON.stringify([]) // 可以后续计算缺失技能
          ]
        );
      } catch (error) {
        console.error('保存匹配结果失败:', error);
      }
    });
    
    await Promise.all(savePromises);
    
    console.log(`为用户 ${userId} 生成了 ${topMatches.length} 个职业推荐`);
    
    res.json({
      success: true,
      matches: topMatches.map(match => ({
        career: {
          id: match.career.id,
          title: match.career.title,
          category: match.career.category,
          description: match.career.description,
          requirements: match.career.requirements,
          salary_range: match.career.salary_range,
          education_level: match.career.education_level,
          experience_years: match.career.experience_years,
          skills: match.career.skills,
          growth_prospects: match.career.growth_prospects
        },
        matchScore: match.totalScore,
        scoreBreakdown: match.scores,
        fileAnalysis: fileAnalysis
      })),
      total: careers.length,
      analyzed: topMatches.length
    });
    
  } catch (error) {
    console.error('获取职业匹配失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '获取职业匹配失败',
      error: error.message 
    });
  }
});

// 获取职业列表（分页）
router.get('/careers', async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 20;
    const category = req.query.category;
    const search = req.query.search;
    
    let sql = 'SELECT * FROM careers WHERE is_active = TRUE';
    let params = [];
    
    if (category) {
      sql += ' AND category = ?';
      params.push(category);
    }
    
    if (search) {
      sql += ' AND (title LIKE ? OR description LIKE ?)';
      params.push(`%${search}%`, `%${search}%`);
    }
    
    sql += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
    params.push(limit, (page - 1) * limit);
    
    const careers = await query(sql, params);
    
    // 获取总数
    let countSql = 'SELECT COUNT(*) as total FROM careers WHERE is_active = TRUE';
    let countParams = [];
    
    if (category) {
      countSql += ' AND category = ?';
      countParams.push(category);
    }
    
    if (search) {
      countSql += ' AND (title LIKE ? OR description LIKE ?)';
      countParams.push(`%${search}%`, `%${search}%`);
    }
    
    const countResult = await query(countSql, countParams);
    const total = countResult[0].total;
    
    res.json({
      success: true,
      careers,
      pagination: {
        page,
        limit,
        total,
        pages: Math.ceil(total / limit)
      }
    });
    
  } catch (error) {
    console.error('获取职业列表失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '获取职业列表失败' 
    });
  }
});

// 获取职业分类（不需要认证）
router.get('/categories', async (req, res) => {
  try {
    const categories = await query(
      'SELECT DISTINCT category FROM careers WHERE is_active = TRUE ORDER BY category',
      []
    );
    
    res.json({
      success: true,
      categories: categories.map(cat => cat.category)
    });
    
  } catch (error) {
    console.error('获取职业分类失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '获取职业分类失败' 
    });
  }
});

// 生成试炼题目
router.post('/trial/question', authenticateToken, async (req, res) => {
  try {
    const { careerId } = req.body;
    
    if (!careerId) {
      return res.status(400).json({
        success: false,
        message: '缺少职业ID'
      });
    }

    // 获取职业信息
    const careers = await query(`
      SELECT * FROM careers WHERE id = ? AND is_active = 1
    `, [careerId]);

    if (careers.length === 0) {
      return res.status(404).json({
        success: false,
        message: '职业不存在'
      });
    }

    const career = careers[0];
    
    // 解析技能数据
    let skills = [];
    try {
      if (career.skills) {
        if (typeof career.skills === 'string') {
          skills = JSON.parse(career.skills);
        } else if (Array.isArray(career.skills)) {
          skills = career.skills;
        }
      }
    } catch (error) {
      console.error('解析技能数据失败:', error);
      skills = [];
    }

    // 调用AI生成题目
    const response = await axios.post('https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation', {
      model: 'qwen-turbo',
      input: {
        messages: [
          {
            role: 'user',
            content: `请为"${career.title}"这个职业生成一个专业的技术面试题或案例分析题。要求：
1. 题目要体现该职业的核心技能和实际工作场景
2. 难度适中，适合有一定基础的求职者
3. 题目要具体明确，便于理解和回答
4. 只返回题目内容，不要包含答案或解析

职业信息：
- 职位：${career.title}
- 分类：${career.category}
- 描述：${career.description}
- 技能要求：${skills.join(', ')}`
          }
        ]
      },
      parameters: {
        temperature: 0.7,
        max_tokens: 500
      }
    }, {
      headers: {
        'Authorization': `Bearer ${process.env.ALIYUN_API_KEY}`,
        'Content-Type': 'application/json'
      }
    });

    if (response.data.output && response.data.output.text) {
      res.json({
        success: true,
        question: response.data.output.text
      });
    } else {
      res.status(500).json({
        success: false,
        message: '生成题目失败'
      });
    }
  } catch (error) {
    console.error('生成题目失败:', error);
    res.status(500).json({
      success: false,
      message: '生成题目失败'
    });
  }
});

// 评测答案
router.post('/trial/evaluate', authenticateToken, async (req, res) => {
  try {
    const { careerId, question, answer } = req.body;
    
    if (!careerId || !question || !answer) {
      return res.status(400).json({
        success: false,
        message: '缺少必要参数'
      });
    }

    // 获取职业信息
    const careers = await query(`
      SELECT * FROM careers WHERE id = ? AND is_active = 1
    `, [careerId]);

    if (careers.length === 0) {
      return res.status(404).json({
        success: false,
        message: '职业不存在'
      });
    }

    const career = careers[0];

    // 调用AI评测答案
    const response = await axios.post('https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation', {
      model: 'qwen-turbo',
      input: {
        messages: [
          {
            role: 'user',
            content: `请对以下职业面试题的回答进行评分和反馈：

职业：${career.title}
题目：${question}
用户答案：${answer}

请从以下维度进行评分（每项0-20分，总分100分）：
1. 技术准确性（20分）
2. 逻辑清晰度（20分）
3. 实用性（20分）
4. 创新性（15分）
5. 表达完整性（15分）
6. 专业深度（10分）

请返回JSON格式的评分结果：
{
  "totalScore": 总分(0-100),
  "scores": {
    "technicalAccuracy": 技术准确性得分,
    "logicClarity": 逻辑清晰度得分,
    "practicality": 实用性得分,
    "innovation": 创新性得分,
    "completeness": 表达完整性得分,
    "professionalDepth": 专业深度得分
  },
  "feedback": "详细的评价反馈和建议"
}`
          }
        ]
      },
      parameters: {
        temperature: 0.3,
        max_tokens: 800
      }
    }, {
      headers: {
        'Authorization': `Bearer ${process.env.ALIYUN_API_KEY}`,
        'Content-Type': 'application/json'
      }
    });

    if (response.data.output && response.data.output.text) {
      try {
        let text = response.data.output.text;
        // 处理markdown代码块
        if (text.includes('```json')) {
          text = text.replace(/```json\n?/g, '').replace(/```\n?/g, '');
        }
        const result = JSON.parse(text);
        res.json({
          success: true,
          evaluation: result
        });
      } catch (parseError) {
        console.error('解析评分结果失败:', parseError);
        res.status(500).json({
          success: false,
          message: '评分解析失败'
        });
      }
    } else {
      res.status(500).json({
        success: false,
        message: '评分失败'
      });
    }
  } catch (error) {
    console.error('评测答案失败:', error);
    res.status(500).json({
      success: false,
      message: '评测答案失败'
    });
  }
});

module.exports = router;
